package com.ycj.entropy.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.ycj.entropy.CreateStudyActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import static android.widget.Toast.LENGTH_SHORT;

public class CameraUtil {
    /*use to caching filename before returning camera*/
    private static String filename;
    private static final String AUTHORITY_STR = "com.ycj.entropy";
    private static final String FILENAME_PREFIX = "entropy";
    public static final int TACKING_PICTURE_REQUEST_CODE = 100;


    /**
     * start taking a picture
     */
    public static String takePicture(Activity activity) {
        /*check permission*/
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, TACKING_PICTURE_REQUEST_CODE);
        }

        /*tacking*/
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {

            try {
                File file = createImageFile(activity);
                if (file != null) {
                    Uri uri = FileProvider.getUriForFile(activity, AUTHORITY_STR, file);

                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    activity.startActivityForResult(takePictureIntent, TACKING_PICTURE_REQUEST_CODE);
                    CameraUtil.filename = file.getName();
                    System.out.println("create image at " + file.getAbsolutePath());

                    return CameraUtil.filename;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return "";
    }

    /**
     * get picture you just taken
     */
    public static Bitmap getImageThumbnail(Context context) {
        String path = String.format("%s/%s", storageTempDir(context).getAbsolutePath(), CameraUtil.filename);
        return getImageThumbnail(path, 200, 200);
    }

    /**
     * get picture you just taken
     */
    public static Bitmap getImageThumbnail(Context context, int width, int height) {
        String path = String.format("%s/%s", storageTempDir(context).getAbsolutePath(), CameraUtil.filename);
        return getImageThumbnail(path, width, height);
    }

    /**
     * get picture of path that you specified
     */
    public static Bitmap getImageThumbnail(File dir, String filename, int width, int height) {
        return getImageThumbnail(new File(dir, filename).getAbsolutePath(), width, height);
    }

    /**
     * get picture of path that you specified
     */
    public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inJustDecodeBounds = false;
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = Math.min(beWidth, beHeight);
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    /**
     * move files from temp to durable directory,
     * where files' name in specified filenames
     */
    public static void saveFiles(Context context, List<String> filenames) {
        File tempDir = storageTempDir(context);
        File[] toSaveFiles = tempDir.listFiles((dir, name) -> filenames.contains(name));

        for (File file : Objects.requireNonNull(toSaveFiles)) {
            boolean b = file.renameTo(new File(storageDir(context), file.getName()));
            if (!b) {
                Toast.makeText(context, "fail to save file: " + file.getName(), LENGTH_SHORT).show();
            }
        }

        tempDir.delete();
    }

    public static File storageDir(Context context) {
        return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }


    private static File createImageFile(Context context) {
        try {
            return File.createTempFile(FILENAME_PREFIX, ".jpg", storageTempDir(context));
        } catch (IOException e) {
            Toast.makeText(context, "fail to create file", LENGTH_SHORT).show();
            e.printStackTrace();
            return null;
        }
    }


    private static File storageTempDir(Context context) {
        File file = storageDir(context);
        File temp = new File(file, "temp");
        if (!temp.exists()) {
            temp.mkdir();
        }
        return temp;
    }

    public static String getFilename() {
        return filename;
    }


}
